package com.duying.gdc.manager;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts.upload.FormFile;

import com.busi.framework.base.PageSupport;
import com.busi.utils.tools.DateTools;
import com.busi.utils.tools.StringTools;
import com.duying.gdc.GdBaseManager;
import com.duying.gdc.action.form.GdMcImportForm;
import com.duying.gdc.model.GdMcImport;
import com.duying.gdc.model.GdMcPerson;

public class GdMcImportManager extends GdBaseManager{
	
	public PageSupport getPage(Map map){
		return this.gdMcImportDao.getPage(map);
	}
	
	public GdMcImport getObjByDate(Date adate){
		String hql = "from GdMcImport gmi where gmi.import_date =:import_date";
		Map map = new HashMap();
		map.put("import_date", adate);
		Object obj = this.baseDao.getUniqueBy(hql, map);
		if(obj == null){
			return null;
		}else{
			return (GdMcImport)obj;
		}
	}
	
	public void saveToDb(GdMcImportForm gmiForm){
		GdMcImport gmi = new GdMcImport();
		gmi.setImport_date(DateTools.stringToDate(gmiForm.getStr_import_date(), DateTools.FULL_YM));
		gmi.setGd_number(gmiForm.getGd_number());
		gmi.setJg_number(gmiForm.getJg_number());
		gmi.setJg_gp_number(gmiForm.getJg_gp_number());
		this.baseDao.saveOrUpdateLog(gmi);
		Integer totalCgsl = 0;
		try{
			FormFile ff = gmiForm.getFormFile();
			InputStreamReader isr = new InputStreamReader(ff.getInputStream());
			BufferedReader br = new BufferedReader(isr);
			String aline = br.readLine();
			String[] cellValue;
			while(aline != null){
				cellValue = aline.split(",");
				GdMcPerson gmp = new GdMcPerson();
				gmp.setXh(StringTools.formatStr2Int(cellValue[0]));
				gmp.setZqzh(cellValue[1]);
				gmp.setGdmc(cellValue[2]);
				gmp.setZjhm(cellValue[3]);
				Integer cgsl = StringTools.formatStr2Int(cellValue[4]);
				totalCgsl += cgsl;
				gmp.setCgsl(cgsl);
				gmp.setCgbl(cellValue[5]);
				gmp.setGdMcImport(gmi);
				this.baseDao.saveOrUpdateLog(gmp);
				aline = br.readLine();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		gmi.setGp_number(totalCgsl);
		this.baseDao.saveOrUpdateLog(gmi);
		
	}

	public List getLastThirteenImport(Date import_date){
		String hql = "from GdMcImport gmi where gmi.import_date <=:import_date order by gmi.import_date desc";
		Map map = new HashMap();
		map.put("import_date", import_date);
		return this.baseDao.findPageByHql(hql, 13, 1, map).getItems();
	}
}
